package com.boot.unity.api.wx.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boot.unity.api.wx.dto.PrePayDto;
import com.boot.unity.api.wx.dto.ResponseBean;
import com.boot.unity.api.wx.entity.TrainStu;
import com.boot.unity.api.wx.utils.IpAddress;
import com.boot.unity.api.wx.utils.PayUtil;
import com.boot.unity.api.wx.utils.ResponseUtil;
import com.boot.unity.api.wx.utils.WxOcrIdCardResults;
import me.chanjar.weixin.common.error.WxErrorException;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class WxSignUpService {
    @Autowired
    private PayUtil payUtil;

    @Value("${serv.servurl}")
    private String servurl;

    @Autowired
    private WxOcrService wxOcrService;

    public Object getPublicKey() {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/json");
        //设置请求头和数据
        RequestBody body = RequestBody.create(mediaType,"");
        //设置地址，方法，数据格式
        Request request = new Request.Builder()
                .url(servurl+ "/wx/signUp/getPublicKey")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        String strResult = "";
        try {
            Response response = client.newCall(request).execute();
            strResult = response.body().string();
            if (response.isSuccessful()) {
                // 接口调用成功
                JSONObject json = JSONObject.parseObject(strResult);
                return json;
            } else {
                //接口调用失败
                JSONObject resurt = new JSONObject();
                resurt.put("errno", "403");
                resurt.put("errmsg", "接口访问失败");
                return resurt;
            }
        } catch (IOException e) {
            e.printStackTrace();
            JSONObject resurt = new JSONObject();
            resurt.put("errno", "403");
            resurt.put("errmsg", e.getMessage());
            return resurt;
        }
    }

    public Object save(TrainStu stu) {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/json");
        JSONObject jsonObject = (JSONObject) JSON.toJSON(stu);
        //设置请求头和数据
        RequestBody body = RequestBody.create(mediaType,jsonObject.toString());
        //设置地址，方法，数据格式
        Request request = new Request.Builder()
                .url(servurl+ "/wx/signUp/save")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        String strResult = "";
        try {
            Response response = client.newCall(request).execute();
            strResult = response.body().string();
            if (response.isSuccessful()) {
                // 接口调用成功
                JSONObject json = JSONObject.parseObject(strResult);
                return json;
            } else {
                //接口调用失败
                JSONObject resurt = new JSONObject();
                resurt.put("errno", "403");
                resurt.put("errmsg", "接口访问失败");
                return resurt;
            }
        } catch (IOException e) {
            e.printStackTrace();
            JSONObject resurt = new JSONObject();
            resurt.put("errno", "403");
            resurt.put("errmsg", e.getMessage());
            return resurt;
        }
    }

    public Object ocrIdCard(String url) {
        //url="https://www.rzsjpkythfwpt.com//wx/storage/fetch/8drut0rcqqdsu3kpbhuo.jpg";//国徽照片
        //url="https://www.rzsjpkythfwpt.com/wx/storage/fetch/6oudc4b6gr9am79igukb.jpg";//人像照片
        //url="https://www.rzsjpkythfwpt.com/wx/storage/fetch/ymgn97yoe5xv1g9awf9g.jpg";//非证件照片

        //发送请求
        WxOcrIdCardResults result = null;
        try {
            result = wxOcrService.idCard(url);
            //System.out.println(result + "-----");
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        if (result == null) {
            return ResponseUtil.fail(1, "请上传正确的身份证件");
        }

        //type=Both, name=某某某, id=11010277771100888X, addr=省级行政区名称-区县级行政区名称具体住宿地址, gender=男, nationality=汉, validDate=
        Map<Object, Object> rtnResult = new HashMap<Object, Object>();
        if (result.getType().toUpperCase().equals("BOTH") || result.getType().toUpperCase().equals("FRONT")) { //人像面  官方给出FRONT为人像面，测试身份图片返回both
            rtnResult.put("name", result.getName());
            rtnResult.put("id", result.getId());
            rtnResult.put("gender", result.getGender());
            rtnResult.put("nationality", result.getNationality());
            rtnResult.put("addr", result.getAddr());
        } else {
            rtnResult.put("name", "null");
            rtnResult.put("id", "null");
        }
        return ResponseUtil.ok(rtnResult);
    }

    public Object detail(String uid, String key) {
        OkHttpClient client = new OkHttpClient();
        String url = servurl+ "/wx/signUp/detail?uid=" + uid + "&key=" + key;
        Request request = new Request.Builder()
                .url(url)
                .build();
        String strResult = "";
        try {
            Response response = client.newCall(request).execute();
            strResult = response.body().string();
            if (response.isSuccessful()) {
                // 接口调用成功
                JSONObject json = JSONObject.parseObject(strResult);
                return json;
            } else {
                //接口调用失败
                JSONObject resurt = new JSONObject();
                resurt.put("errno", "403");
                resurt.put("errmsg", "接口访问失败");
                return resurt;
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject resurt = new JSONObject();
            resurt.put("errno", "403");
            resurt.put("errmsg", e.getMessage());
            return resurt;
        }
    }

    public Object update(TrainStu stu) {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/json");
        JSONObject jsonObject = (JSONObject) JSON.toJSON(stu);
        //设置请求头和数据
        RequestBody body = RequestBody.create(mediaType,jsonObject.toString());
        //设置地址，方法，数据格式
        Request request = new Request.Builder()
                .url(servurl+ "/wx/signUp/update")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        String strResult = "";
        try {
            Response response = client.newCall(request).execute();
            strResult = response.body().string();
            if (response.isSuccessful()) {
                // 接口调用成功
                JSONObject json = JSONObject.parseObject(strResult);
                return json;
            } else {
                //接口调用失败
                JSONObject resurt = new JSONObject();
                resurt.put("errno", "403");
                resurt.put("errmsg", "接口访问失败");
                return resurt;
            }
        } catch (IOException e) {
            e.printStackTrace();
            JSONObject resurt = new JSONObject();
            resurt.put("errno", "403");
            resurt.put("errmsg", e.getMessage());
            return resurt;
        }
    }

    public Object getStepByUid(String uid, String key) {
        OkHttpClient client = new OkHttpClient();
        String url = servurl+ "/wx/signUp/getStepByUid?uid=" + uid + "&key=" + key;
        Request request = new Request.Builder()
                .url(url)
                .build();
        String strResult = "";
        try {
            Response response = client.newCall(request).execute();
            strResult = response.body().string();
            if (response.isSuccessful()) {
                // 接口调用成功
                JSONObject json = JSONObject.parseObject(strResult);
                return json;
            } else {
                //接口调用失败
                JSONObject resurt = new JSONObject();
                resurt.put("errno", "403");
                resurt.put("errmsg", "接口访问失败");
                return resurt;
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject resurt = new JSONObject();
            resurt.put("errno", "403");
            resurt.put("errmsg", e.getMessage());
            return resurt;
        }
    }

    public Object getClassType(Integer id, String carModel) {
        OkHttpClient client = new OkHttpClient();
        String url = servurl+ "/wx/signUp/getClassType?id=" + id + "&carModel=" + carModel;
        Request request = new Request.Builder()
                .url(url)
                .build();
        String strResult = "";
        try {
            Response response = client.newCall(request).execute();
            strResult = response.body().string();
            if (response.isSuccessful()) {
                // 接口调用成功
                JSONObject json = JSONObject.parseObject(strResult);
                return json;
            } else {
                //接口调用失败
                JSONObject resurt = new JSONObject();
                resurt.put("errno", "403");
                resurt.put("errmsg", "接口访问失败");
                return resurt;
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject resurt = new JSONObject();
            resurt.put("errno", "403");
            resurt.put("errmsg", e.getMessage());
            return resurt;
        }
    }

    public Object getPayParam(String uid, String key) {
        OkHttpClient client = new OkHttpClient();
        String url = servurl+ "/wx/signUp/getPayParam?uid=" + uid + "&key=" + key;
        Request request = new Request.Builder().url(url).build();
        String strResult = "";
        try {
            Response response = client.newCall(request).execute();
            strResult = response.body().string();
            if (response.isSuccessful()) {
                // 接口调用成功
                JSONObject json = JSONObject.parseObject(strResult);
                return json;
            } else {
                //接口调用失败
                JSONObject resurt = new JSONObject();
                resurt.put("errno", "403");
                resurt.put("errmsg", "接口访问失败");
                return resurt;
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject resurt = new JSONObject();
            resurt.put("errno", "403");
            resurt.put("errmsg", e.getMessage());
            return resurt;
        }
    }

    public Object getStep(String uid, String key) {
        OkHttpClient client = new OkHttpClient();
        String url = servurl+ "/wx/signUp/getStep?uid=" + uid + "&key=" + key;
        Request request = new Request.Builder()
                .url(url)
                .build();
        String strResult = "";
        try {
            Response response = client.newCall(request).execute();
            strResult = response.body().string();
            if (response.isSuccessful()) {
                // 接口调用成功
                JSONObject json = JSONObject.parseObject(strResult);
                return json;
            } else {
                //接口调用失败
                JSONObject resurt = new JSONObject();
                resurt.put("errno", "403");
                resurt.put("errmsg", "接口访问失败");
                return resurt;
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject resurt = new JSONObject();
            resurt.put("errno", "403");
            resurt.put("errmsg", e.getMessage());
            return resurt;
        }
    }

    public Object getStuClassTypeInfo(String uid, String key) {
        OkHttpClient client = new OkHttpClient();
        String url = servurl+ "/wx/signUp/getStuClassTypeInfo?uid=" + uid + "&key=" + key;
        Request request = new Request.Builder()
                .url(url)
                .build();
        String strResult = "";
        try {
            Response response = client.newCall(request).execute();
            strResult = response.body().string();
            if (response.isSuccessful()) {
                // 接口调用成功
                JSONObject json = JSONObject.parseObject(strResult);
                return json;
            } else {
                //接口调用失败
                JSONObject resurt = new JSONObject();
                resurt.put("errno", "403");
                resurt.put("errmsg", "接口访问失败");
                return resurt;
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject resurt = new JSONObject();
            resurt.put("errno", "403");
            resurt.put("errmsg", e.getMessage());
            return resurt;
        }
    }

    public Object savePayInfo(Integer stuId, String serviceCode, String traceID, String message, String result) {
        OkHttpClient client = new OkHttpClient();
        String url = servurl+ "/wx/signUp/savePayInfo?stuId=" + stuId + "&serviceCode=" + serviceCode+ "&traceID=" +traceID+"&message=" +message+"&result=" +result;
        Request request = new Request.Builder()
                .url(url)
                .build();
        String strResult = "";
        try {
            Response response = client.newCall(request).execute();
            strResult = response.body().string();
            if (response.isSuccessful()) {
                // 接口调用成功
                JSONObject json = JSONObject.parseObject(strResult);
                return json;
            } else {
                //接口调用失败
                JSONObject resurt = new JSONObject();
                resurt.put("errno", "403");
                resurt.put("errmsg", "接口访问失败");
                return resurt;
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject resurt = new JSONObject();
            resurt.put("errno", "403");
            resurt.put("errmsg", e.getMessage());
            return resurt;
        }
    }

    public ResponseBean prePay(PrePayDto payDto) {
        return payUtil.invokeSHFW00009(payDto.getCommID(), payDto.getBody(), payDto.getReqTime(),payDto.getTraceRecordDTO());
    }
}
